// pages/search/search.js
Page({
    data: {
      baseURL: 'http://43.139.97.111:8080',
      shoopingtext: "", //搜索框的值
      history: true, //显示历史记录
      noneview: false, //显示未找到提示
      shoppinglist: false, //显示商品列表
      historyArray: [], //历史记录数组,
      searchList: []
    },
    //清除历史记录
    cleanhistory: function(e) {
      this.setData({
        history: true, //隐藏历史记录
        historyArray: [], //清空历史记录数组
        shoopingtext: "" //清空搜索框
      })
      wx.removeStorage({
        key: 'history',
        success (res) {
          console.log(res)
        }
      })
    },
    //搜索
    search: function(e) {
      var _this=this;
      var searchtext = this.data.shoopingtext; //搜索框的值
      var sss = true;
      if (searchtext != "") {
        //将搜索框的值赋给历史数组
        
        _this.historyHandle(searchtext);
        wx.showLoading({
          title: '加载中',
          mask:true
        })
        wx.request({
          url: 'http://43.139.97.111:8080/books/queryByKeyWork?keyWork='+searchtext,
          header: {
            'content-type': 'application/json' // 默认值
          },
          success (res) {
            console.log(res.data);
            if(res.statusCode==200){
              _this.setData({
                searchList:res.data.data
              })
            }
            wx.hideLoading()
          }
        })
        sss=false
        this.setData({
          history: false, //隐藏历史记录
          noneview: sss, //隐藏未找到提示
          shoppinglist: true, //显示商品列表
        })
      } else {
        this.setData({
          noneview: true, //显示未找到提示
          shoppinglist: false, //隐藏商品列表
          history: false, //隐藏历史记录
        })
      }
    },
  
    historyHandle(searchtext) {
      let history = this.data.historyArray;
      const idx = history.indexOf(searchtext);
      if (idx === -1) {
          // 搜索记录只保留8个
          if (history.length > 7) {
              history.pop();
          }
      } else {
          history.splice(idx, 1);
      }
      history.unshift(searchtext);
      wx.setStorageSync('history', JSON.stringify(history));
  },
  onLoad() {
      const history = wx.getStorageSync('history');
      if (history) {
          this.setData({
              historyArray: JSON.parse(history)
          })
          console.log(this.data.historyArray);
      }
  },
  
    //搜索框的值
    shoppinginput: function(e) {
      //当删除input的值为空时
      if (e.detail.value == "") {
        this.setData({
          history: true, //显示历史记录
          shoppinglist: false //隐藏商品列表
        });
        //所有商品列表的状态改为0
        for (var index in this.data.searchList) {
          let temp = 'searchList[' + index + '].bookStatus';
          this.setData({
            [temp]: 0,
          })
        }
      }
      this.setData({
        shoopingtext: e.detail.value
      })
      this.onLoad()
    },
    //点击历史记录赋值给搜索框
    textfz: function(e) {
      this.setData({
        shoopingtext: e.target.dataset.text,
      })
    }
  })